﻿using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

    public GameObject player;
    public float rotationspeed;
    public float goalRotation;
    public GameObject platformManager;
    public GameObject muzzlePosition;

    private PlayerBehaviour playerScript;
    private int sign;
    private bool initRotation = false;


	// Use this for initialization
    void Start()
    {
        goalRotation = transform.rotation.y;
	}
	
	// Update is called once per frame
	void FixedUpdate () 
    {

        if (Mathf.Abs(transform.eulerAngles.y - muzzlePosition.transform.eulerAngles.y) > 0.001)
        {

            if (!initRotation)
            {
                player.SendMessage("setInRotation", true);
                initRotation = true;
            }
            transform.Rotate(Vector3.up * rotationspeed * sign);
            player.transform.rotation = transform.rotation;
        }
        else if (initRotation)
        {

            platformManager.SendMessage("updatePlatformColliders", getOrientation());
            initRotation = false;
            player.transform.rotation = muzzlePosition.transform.rotation;
            player.SendMessage("setInRotation", false);
        }


        if (Input.GetButtonDown("Fire2"))
        {
            turnRight();
        }
        if (Input.GetButtonDown("Fire1"))
        {
            turnLeft();
        }
	}

    public Vector3 getOrientation()
    {
        Vector3 orientation;
        if (muzzlePosition.transform.rotation.y == 0 || muzzlePosition.transform.rotation.y == 180)
            orientation = new Vector3(0, 0, 1);
        else
            orientation = new Vector3(1, 0, 0);
        return orientation;
    }

    public void turnRight()
    {
        sign = -1;
        muzzlePosition.transform.Rotate(Vector3.up * (-90), Space.Self);
    }

    public void turnLeft()
    {
        sign = 1;
        muzzlePosition.transform.Rotate(Vector3.up * (90), Space.Self);
    }
}
